import type { RouteRecordRaw } from 'vue-router'

import { usePermissionStoreWithOut } from '@/store/modules/permission'
import { useNProgress } from '@fl/hooks/web/useNProgress'
import { usePageLoading } from '@fl/hooks/web/usePageLoading'
import { useTitle } from '@fl/hooks/web/useTitle'
import { useUserStoreWithOut } from '@fl/store/modules/user'

import router from './router'

const { done, start } = useNProgress()

const { loadDone, loadStart } = usePageLoading()

router.beforeEach(async (to, from, next) => {
    start()
    loadStart()
    const permissionStore = usePermissionStoreWithOut()
    const userStore = useUserStoreWithOut()

    if (userStore.getUserInfo) {
        if (to.path === '/login') {
            next({ path: '/' })
        }
        else {
            if (permissionStore.getIsAddRouters) {
                next()
                return
            }

            // 开发者可根据实际情况进行修改
            const roleRouters = userStore.getRoleRouters || []

            // 是否使用动态路由
            // ! 先用前端模式, 时间宽裕改成后端 crud 菜单
            await permissionStore.generateRoutes('frontEnd', roleRouters as string[])

            permissionStore.getAddRouters.forEach((route) => {
                router.addRoute(route as unknown as RouteRecordRaw) // 动态添加可访问路由表
            })

            const redirectPath = from.query.redirect || to.path
            const redirect = decodeURIComponent(redirectPath as string)

            // 初始进入路由时候的精准分片
            let nextData
            let pathPrefix
            if (to.path === redirect) {
                nextData = { ...to, replace: true }
                pathPrefix = to.fullPath.match(/^\/[^/]+/)?.[0]
            }
            else {
                nextData = { path: redirect }
                pathPrefix = redirect!.match(/^\/[^/]+/)?.[0]
            }

            permissionStore.setSliceRouters(pathPrefix ?? '/')
            permissionStore.setIsAddRouters(true)
            next(nextData)
        }
    }
    else {
        next()
    }
})

router.afterEach((to) => {
    useTitle(to?.meta?.title as string)
    done() // 结束Progress
    loadDone()
})
